package com.google.appengine.echogear;

import java.io.IOException;
import java.util.Collection;
import java.util.logging.Logger;

import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.google.appengine.api.datastore.Entity;
import com.google.appengine.api.xmpp.Message;
import com.google.appengine.api.xmpp.MessageBuilder;
import com.google.appengine.api.xmpp.XMPPService;
import com.google.appengine.api.xmpp.XMPPServiceFactory;
import com.google.appengine.echogear.core.Cache;
import com.google.appengine.echogear.core.EchoJob;
import com.google.appengine.echogear.core.Register;

public class EchoGearServlet extends HttpServlet {

	private static final long serialVersionUID = -8255817748131639811L;
	
	private static final Logger log = Logger.getLogger(EchoGearServlet.class.getName());

	@Override
	public void init(ServletConfig servletConfig) throws ServletException {
		super.init(servletConfig);
		Iterable<Entity> result = Register.load();
		for(Entity record : result) {
			try {
				Object name = record.getProperty("name");
				Object className = record.getProperty("class");
				Object param = record.getProperty("param");		
				Object user = record.getProperty("user");	
				EchoJob echoJob = (EchoJob)Class.forName((String) className).newInstance();
				echoJob.setName((String) name);
				echoJob.setParam((String) param);
				echoJob.setUser((String) user);
				if(echoJob.init()) {
					Cache.add((String)name, echoJob);
				} else {
					continue;
				}
			} catch (ClassNotFoundException e) {
				continue;
			} catch (InstantiationException e) {
				continue;
			} catch (IllegalAccessException e) {
				continue;
			}
		}
		
				
	}

	public void doPost(HttpServletRequest req, HttpServletResponse res)
			throws IOException {
		XMPPService xmpp = XMPPServiceFactory.getXMPPService();
		Message message = xmpp.parseMessage(req);
		
		Message msg = new MessageBuilder()
		.withRecipientJids(message.getFromJid())
        .withBody("roger that")
        .build();

        if (xmpp.getPresence(message.getFromJid()).isAvailable()) {
        	xmpp.sendMessage(msg);
        }
		
		Collection<?> jobs = Cache.load();
		String responseMsg;
		for(Object job : jobs) {
			EchoJob echoJob = (EchoJob) job;
			log.severe("name:" + echoJob.getName());
			log.severe("send:" + message.getFromJid().getId().split("/")[0]);
			log.severe("job:" + echoJob.getUser());
			if(!message.getFromJid().getId().split("/")[0].equals(echoJob.getUser()))
				continue;
           
			boolean isSuccess = echoJob.send(new String(message.getBody().getBytes("UTF-8"), "UTF-8"));
			if(isSuccess)
				responseMsg = "++name++ send is success".replace("++name++", echoJob.getName());
			else
				responseMsg = "++name++ send is failure".replace("++name++", echoJob.getName());
			
			msg = new MessageBuilder()
			.withRecipientJids(message.getFromJid())
            .withBody(responseMsg)
            .build();

	        if (xmpp.getPresence(message.getFromJid()).isAvailable()) {
	        	xmpp.sendMessage(msg);
	        }
	        	
		}
	}

}